var http = require('http');
var relation = require('../proxy/relation');
var faction = require('../proxy/faction');
var logger = require('./Logger');

http.createServer(function(req, res){
    var buf = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){
        buf += chunk;
    });
    req.on('end', function(){
        //console.log(buf);
        var data = JSON.parse(buf);
        if(data.faction){
            addFactionRelations(data, function(){
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end('ok world ~');
            })
        }else{
            addAttendsRelations(data, function(){
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end('ok world ~');
            })
        }
        /*test(data, function(){
            res.writeHead(200, {'Content-Type': 'application/json'});
            res.end('ok world ~');
        })*/

    });
}).listen('8765', '127.0.0.1');

function test(data, cb){
    for(var j= 0,len=100; j<len; j++){
        (function(index){
            relation.testChildRelation(index, function(){});
        })(j);
    }
    cb();
}

/**
 * 处理添加关系
 * @param data
 * @param callback
 */
function addAttendsRelations(data, callback){
    var attends = data.attends,
        userId = data.userId;
    for(var j= 0,len=attends.length; j<len; j++){
        (function(targetUser){
            relation.addRelationWeight(targetUser.id, userId, 1, function(err, data){
                if(err) logger.error(err.message);
                logger.debug('['+targetUser.id+'] and ['+userId+'] add relation ---- '+1);
            })
        })(attends[j]);
    }
    callback()
}
function addFactionRelations(data, callback){
    var factionId = data.factionId,
        userId = data.userId;
    faction.getAllMembers(factionId, function(err, fms){
        var len = fms.length;
        for(var i=0; i<len; i++){
            (function(memberId){
                // 加入一个圈子 关系权重+10
                relation.addRelationWeight(userId, memberId, 10, function(err, resp){
                    if(resp)
                        console.log('完成圈关系增加:'+resp);// 完成
                })
            })(fms[i].member.id);
        }
        callback();
    })
}